package com.ruoyi.web.controller.admin.contract;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.dto.ContractCreateDTO;
import com.ruoyi.system.dto.ContractDTO;
import com.ruoyi.system.dto.ContractUpdateDTO;
import com.ruoyi.system.dto.ContractAuditDTO;
import com.ruoyi.system.service.ContractFileService;
import com.ruoyi.system.service.ContractService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/admin/contracts")
@RequiredArgsConstructor
public class ContractController extends BaseController {

    @Resource
    private ContractService contractService;

    @Resource
    private ContractFileService contractFileService;

    /**
     * 根据ID获取合同
     */
    @GetMapping("/getContractDetail/{id}")
    public AjaxResult getContract(@PathVariable Long id) {
        ContractDTO contractDTO = contractService.getById(id);
        return AjaxResult.success(contractDTO);
    }

    /**
     * 获取所有合同
     */
    @GetMapping
    public AjaxResult getAllContracts() {
        List<ContractDTO> contractDTOList = contractService.listAll();
        return AjaxResult.success(contractDTOList);
    }

    /**
     * 根据合同类型查询合同
     */
    @GetMapping("/type/{type}")
    public AjaxResult getContractsByType(@PathVariable String type) {
        List<ContractDTO> contractDTOList = contractService.getByContractType(type);
        return AjaxResult.success(contractDTOList);
    }

    @PostMapping(value = "/add")
    public AjaxResult addContract(@RequestBody @Valid ContractCreateDTO dto) {
        // 调用服务层执行新增逻辑
        ContractDTO createdContract = contractService.createWithFiles(dto);
        return AjaxResult.success("合同创建成功", createdContract);
    }

    /**
     * 更新合同
     */
    @PutMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateContract(@RequestBody ContractUpdateDTO dto) {
        ContractDTO updated = contractService.update(dto);
        return AjaxResult.success(updated);
    }

    /**
     * 删除合同
     */
    @DeleteMapping("/delete/{id}")
    public AjaxResult deleteContract(@PathVariable Long id) {
        boolean deleted = contractService.deleteById(id);
        return AjaxResult.success(deleted);
    }

    /**
     * 删除合同文件
     */
    @DeleteMapping("/deleteFile/{fileId}")
    public AjaxResult deleteContractFile(@PathVariable Long fileId) {
        boolean deleted = contractFileService.removeByFileId(fileId);
        return AjaxResult.success(deleted);
    }

    /**
     * 多条件筛选合同集合
     */
    @GetMapping("/listByCondition")
    public AjaxResult listByCondition(
            @RequestParam(required = false) String projectName,
            @RequestParam(required = false) String projectAddress,
            @RequestParam(required = false) String stage,
            @RequestParam(required = false) String projectId,
            @RequestParam(required = false) String contractSigner,
            @RequestParam(required = false) String contractType,
            @RequestParam(required = false) String contractName,
            @RequestParam(required = false) Integer auditStatus,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate signStartDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate signEndDate) {
        List<ContractDTO> contractDTOList = contractService.listByCondition(
                projectId, projectName, projectAddress, stage, contractSigner, contractType,
                contractName, auditStatus, signStartDate, signEndDate);
        return AjaxResult.success(contractDTOList);
    }

    /**
     * 下载合同所有附件的压缩包
     * @param contractId 合同ID
     * @return 压缩包文件流
     */
    @GetMapping("/downloadAttachments/{contractId}")
    public void downloadContractAttachments(@PathVariable Long contractId,
                                            HttpServletResponse response) {
        try {
            contractService.downloadContractAttachmentsAsZip(contractId, response);
        } catch (Exception e) {
            logger.error("下载合同附件压缩包失败，合同ID: {}", contractId, e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 审核通过合同
     * @param auditDTO 审核信息
     * @return 审核结果
     */
    @PostMapping("/audit/approve")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult approveContract(@RequestBody @Valid ContractAuditDTO auditDTO) {
        try {
            contractService.approveContract(auditDTO);
            return AjaxResult.success("合同审核通过成功");
        } catch (Exception e) {
            logger.error("合同审核通过失败，合同ID: {}", auditDTO.getContractId(), e);
            return AjaxResult.error("合同审核通过失败：" + e.getMessage());
        }
    }

    /**
     * 审核拒绝合同
     * @param auditDTO 审核信息
     * @return 审核结果
     */
    @PostMapping("/audit/reject")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult rejectContract(@RequestBody @Valid ContractAuditDTO auditDTO) {
        try {
            contractService.rejectContract(auditDTO);
            return AjaxResult.success("合同审核拒绝成功");
        } catch (Exception e) {
            logger.error("合同审核拒绝失败，合同ID: {}", auditDTO.getContractId(), e);
            return AjaxResult.error("合同审核拒绝失败：" + e.getMessage());
        }
    }
}
